package com.wcs.exam.controller.admin.biz;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.wcs.exam.common.base.BaseBiz;
import com.wcs.exam.common.base.Result;
import com.wcs.exam.common.base.exception.BaseException;
import com.wcs.exam.common.base.page.Page;
import com.wcs.exam.common.base.page.PageUtil;
import com.wcs.exam.common.constant.RedisConstant;
import com.wcs.exam.common.server.upload.UploadService;
import com.wcs.exam.common.util.BeanUtil;
import com.wcs.exam.common.util.JsonUtil;
import com.wcs.exam.controller.admin.req.*;
import com.wcs.exam.controller.admin.resp.AdminMaterialPageResp;
import com.wcs.exam.controller.admin.resp.AdminMaterialPreviewResp;
import com.wcs.exam.controller.admin.resp.AdminMaterialViewResp;
import com.wcs.exam.controller.admin.resp.AdminMaterialVodUploadResp;
import com.wcs.exam.controller.biz.CategoryCommonBiz;
import com.wcs.exam.controller.biz.SysConfigCommonBiz;
import com.wcs.exam.dao.MaterialDao;
import com.wcs.exam.dao.impl.mapper.entity.Material;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Admin-素材信息
 *
 * @author wcs
 * @since 2025-03-24
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminMaterialBiz extends BaseBiz {

    @NotNull
    private final RedissonClient redissonClient;

    @NotNull
    private final UploadService uploadService;

    @NotNull
    private final CategoryCommonBiz categoryCommonBiz;
    @NotNull
    private final SysConfigCommonBiz sysConfigCommonBiz;

    @NotNull
    private final MaterialDao dao;


    /**
     * 素材信息-分页
     *
     * @param req 素材信息-分页查询参数
     * @return 素材信息
     */
    public Result<Page<AdminMaterialPageResp>> page(AdminMaterialPageReq req) {
        Set<Long> categoryIds = new HashSet<>();
        if (ObjectUtil.isNotEmpty(req.getCategoryId())) {
            categoryIds.add(req.getCategoryId());
            List<Long> childrenIdList = categoryCommonBiz.listChildrenIdById(req.getCategoryId());
            if (CollectionUtil.isNotEmpty(childrenIdList)) {
                categoryIds.addAll(childrenIdList);
            }
        }

        // 处理查询条件
        LambdaQueryWrapper<Material> wrapper = new LambdaQueryWrapper<Material>()
                .in(CollectionUtil.isNotEmpty(categoryIds), Material::getCategoryId, categoryIds)
                .eq(ObjectUtil.isNotNull(req.getMaterialType()) && req.getMaterialType() > 0, Material::getMaterialType, req.getMaterialType())
                .like(ObjectUtil.isNotEmpty(req.getMaterialName()), Material::getMaterialName, req.getMaterialName())
                .eq(ObjectUtil.isNotNull(req.getStatus()), Material::getStatus, req.getStatus())
                // 排序
                .orderByDesc(Material::getSort)
                .orderByDesc(Material::getId);

        // 分页查询
        IPage<Material> page = dao.page(PageDTO.of(req.getPageCurrent(), req.getPageSize()), wrapper);
        Page<AdminMaterialPageResp> resp = PageUtil.transform(page, AdminMaterialPageResp.class);
        return Result.success(resp);
    }

    /**
     * 素材信息-添加
     *
     * @param req 素材信息
     * @return 添加结果
     */
    public Result<String> save(AdminMaterialSaveReq req) {
        RLock lock = redissonClient.getLock(RedisConstant.Exam.MATERIAL);
        try {
            boolean lockRes = lock.tryLock(RedisConstant.DEFAULT_WAIT_TIME, RedisConstant.DEFAULT_LEASE_TIME, TimeUnit.SECONDS);
            if (!lockRes) {
                log.warn("素材添加获取锁超时");
                return Result.error(toI18nFail());
            }
            Material material = BeanUtil.copyProperties(req, Material.class);
            material.setSort(dao.getMaxSort() + 1);
            boolean saveRes = dao.save(material);
            return saveRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
        } catch (InterruptedException e) {
            log.error("素材添加失败", e);
            Thread.currentThread().interrupt();
            throw new BaseException(toI18nFail());
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    /**
     * 素材信息-查看
     *
     * @param id 主键ID
     * @return 素材信息
     */
    public Result<AdminMaterialViewResp> view(Long id) {
        Material material = dao.getById(id);
        if (ObjectUtil.isNull(material)) {
            return Result.error("素材信息不存在");
        }
        return Result.success(BeanUtil.copyProperties(material, AdminMaterialViewResp.class));
    }

    /**
     * 素材信息-编辑
     *
     * @param req 素材信息-编辑对象
     * @return 编辑结果
     */
    public Result<String> edit(AdminMaterialEditReq req) {
        // 获取校验素材信息
        Material material = dao.getById(req.getId());
        if (ObjectUtil.isNull(material)) {
            return Result.error("素材信息不存在");
        }

        // 更新素材信息
        Material updateMaterial = BeanUtil.copyProperties(req, Material.class);
        updateMaterial.setGmtCreate(null);
        updateMaterial.setGmtModified(null);
        boolean updateRes = dao.updateById(updateMaterial);
        return updateRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
    }

    /**
     * 素材信息-更新状态
     *
     * @param req 素材信息-更新对象
     * @return 更新结果
     */
    public Result<String> updateStatus(AdminMaterialUpdateStatusReq req) {
        // 获取校验素材信息
        Material material = dao.getById(req.getId());
        if (ObjectUtil.isNull(material)) {
            return Result.error("素材信息不存在");
        }

        // 更新素材信息
        Material updateMaterial = BeanUtil.copyProperties(req, Material.class);
        updateMaterial.setGmtCreate(null);
        updateMaterial.setGmtModified(null);
        boolean updateRes = dao.updateById(updateMaterial);
        return updateRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
    }

    /**
     * 素材信息-排序
     *
     * @param reqs 素材信息-排序对象
     * @return 排序结果
     */
    public Result<String> sort(List<AdminMaterialSortReq> reqs) {
        // 查询获取素材信息
        List<Material> materialList = dao.lambdaQuery()
                .in(Material::getId, reqs.stream().map(AdminMaterialSortReq::getId).collect(Collectors.toSet()))
                .list();
        if (CollectionUtil.isEmpty(materialList)) {
            return Result.success(toI18nSuccess());
        }
        RLock lock = redissonClient.getLock(RedisConstant.Exam.MATERIAL);
        try {
            boolean lockRes = lock.tryLock(RedisConstant.DEFAULT_WAIT_TIME, RedisConstant.DEFAULT_LEASE_TIME, TimeUnit.SECONDS);
            if (!lockRes) {
                log.warn("素材排序获取锁超时");
                return Result.error(toI18nFail());
            }

            dao.lambdaUpdate()
                    .in(Material::getId, materialList.stream().map(Material::getId).collect(Collectors.toSet()))
                    .setDecrBy(Material::getSort, Integer.MAX_VALUE)
                    .update();

            // 处理待更新排序的素材信息
            Map<Long, Integer> sortMap = new HashMap<>();
            reqs.forEach(item -> sortMap.put(item.getId(), item.getSort()));
            List<Material> updateList = new ArrayList<>();
            for (Material material : materialList) {
                Integer sort = sortMap.get(material.getId());
                if (ObjectUtil.isNull(sort)) {
                    continue;
                }

                Material updateMaterial = new Material();
                updateMaterial.setId(material.getId());
                updateMaterial.setSort(sort);
                updateList.add(updateMaterial);
            }

            // 批量更新素材信息排序
            if (CollectionUtil.isNotEmpty(updateList)) {
                dao.updateBatchById(updateList);
            }
            return Result.success(toI18nSuccess());
        } catch (InterruptedException e) {
            log.error("素材排序失败", e);
            Thread.currentThread().interrupt();
            throw new BaseException(toI18nFail());
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    /**
     * 素材信息-删除
     *
     * @param id ID主键
     * @return 删除结果
     */
    public Result<String> delete(Long id) {
        // 获取校验素材信息
        Material material = dao.getById(id);
        if (ObjectUtil.isNull(material)) {
            return Result.error("素材信息不存在");
        }

        // 删除素材信息
        if (dao.removeById(id)) {
            return Result.success(toI18nSuccess());
        }
        return Result.error(toI18nFail());
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<String> batchEdit(AdminMaterialBatchEditReq req) {
        if (CollUtil.isNotEmpty(req.getIds())) {
            List<Material> materialList = new ArrayList<>();
            for (Long id : req.getIds()) {
                Material material = new Material();
                material.setId(id);
                material.setCategoryId(req.getCategoryId());
                materialList.add(material);
            }
            dao.updateBatchById(materialList);
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<String> batchDelete(AdminMaterialBatchDeleteReq req) {
        List<Material> materialList = dao.listByIds(req.getIds());
        if (CollUtil.isEmpty(materialList)) {
            return Result.error("素材不存在");
        }
        for (Material material : materialList) {
            Result<String> result = handleDelete(material);
            if (!result.getCode().equals(Result.SUCCESS)) {
                throw new BaseException(result.getMsg());
            }
        }
        return Result.success("操作成功");
    }

    private Result<String> handleDelete(Material material) {
        if (dao.removeById(material.getId())) {
            // 删除文档
            try {
                uploadService.delete(material.getStoragePlatform(), material.getMaterialUrl(), sysConfigCommonBiz.getUpload());
            } catch (Exception e) {
                log.warn("删除文档失败：{}", JsonUtil.toJsonString(material), e);
            }
        }
        return Result.success("操作成功");
    }

    public Result<AdminMaterialVodUploadResp> vodUpload() {
        AdminMaterialVodUploadResp resp = new AdminMaterialVodUploadResp();
        return Result.success(resp);
    }

    public Result<AdminMaterialPreviewResp> preview(Long id) {
        Material material = dao.getById(id);
        if (ObjectUtil.isNull(material)) {
            return Result.error("素材不存在");
        }
        AdminMaterialPreviewResp resp = new AdminMaterialPreviewResp();
        return Result.success(resp);
    }
}
